# @CreateTime : 2019-11-15 17:19 
# @Author : mayuanbao
# @Desc : 企业信息
import datetime
import time
from selenium.webdriver.common.by import By
from base import Base
import base
from logger import Logger


class EnterpriseInfo(Base):
    """
    企业基本信息
    """
    logger = Logger('EnterpriseInfo').get_log()

    def click_enterprise_info(self):
        """
        点击企业基本信息并切换iframe
        """

        # 刷新页面
        self.refresh()

        self.click((By.CLASS_NAME, 'jbxx'))
        self.switch_to_frame('jbxx')
        time.sleep(1)

    def input_enterprise_name(self, name):
        """
        输入企业名称

        :param name: 企业名称
        :type name: str
        :return: 企业名称
        :rtype: str
        """
        locator = (By.NAME, 'Nsr')
        self.send_keys(locator, name)
        return self.get_attribute(locator)

    def input_create_date(self, option=1):
        """
        输入成立日期

        :param option: 日期
            1：当前日期
            2：16
        :type option: int
        :return: 日期
        :rtype: str
        """
        locator = (By.ID, 'datejbxxsz')
        # self.click(locator)
        self.select_date(locator, option)
        return self.get_attribute(locator)

    def input_real_estate_qualification_number(self, num):
        """
         输入房地产资质号

        :param num: 房地产资质号
        :type num: str
        :return: 房地产资质号
        :rtype: str
        """
        locator = (By.NAME, 'Zzzh')
        self.send_keys(locator, num)
        return self.get_attribute(locator)

    def input_qualification_level(self, level):
        """
        输入资质等级

        :param level: 资质等级
        :type level: str
        :return: 资质等级
        :rtype: str
        """
        locator = (By.NAME, 'Zzdj')
        self.send_keys(locator, level)
        return self.get_attribute(locator)

    def select_industry_type(self, option=1):
        """
        选择行业类型

        :param option: 行业类型，默认 1
            1：房地产业
            2：非房地产业
        :type option: int
        :return: 行业类型
        :rtype: str
        """

        # 点击行业类型
        locator = (
            By.XPATH, "/html[1]/body[1]/div[2]/dl[1]/dd[1]/div[1]/form[1]/div[7]/div[1]/div[1]/div[1]/input[1]")
        self.click(locator)
        # 选择下拉中的行业类型
        xpath = f'/html[1]/body[1]/div[2]/dl[1]/dd[1]/div[1]/form[1]/div[7]/div[1]/div[1]/dl[1]/dd[{option}]'
        self.click((By.XPATH, xpath))
        return self.get_attribute(locator)

    # 输入联系人邮箱
    def input_email(self, email):
        self.send_keys((By.NAME, 'lxryx'), email)
        return self.get_attribute((By.NAME, 'lxryx'), 'value')

    # 输入法人代表
    def input_legal_representative(self, name):
        self.send_keys((By.NAME, 'Frdb'), name)
        return self.get_attribute((By.NAME, 'Frdb'), 'value')

    # 输入法人代表联系方式
    def input_legal_representative_phone_number(self, num):
        self.send_keys((By.NAME, 'Frlxfs'), num)
        return self.get_attribute((By.NAME, 'Frlxfs'), 'value')

    # 输入财务负责人
    def input_financial_admin(self, name):
        self.send_keys((By.NAME, 'Cwfzr'), name)
        return self.get_attribute((By.NAME, 'Cwfzr'), 'value')

    # 输入财务负责人联系方式
    def input_financial_admin_phone_number(self, num):
        self.send_keys((By.NAME, 'Cwlxfs'), num)
        return self.get_attribute((By.NAME, 'Cwlxfs'), 'value')

    # 输入办税人
    def input_tax_people(self, name):
        self.send_keys((By.NAME, 'Bsr'), name)
        return self.get_attribute((By.NAME, 'Bsr'), 'value')

    # 输入办税人联系方式
    def input_tax_people_phone_number(self, num):
        self.send_keys((By.NAME, 'Bsrlxfs'), num)
        return self.get_attribute((By.NAME, 'Bsrlxfs'), 'value')

    # 输入单位地址
    def input_unit_address(self, address):
        self.send_keys((By.NAME, 'Dwdz'), address)
        return self.get_attribute((By.NAME, 'Dwdz'), 'value')

    # 输入单位网址
    def input_unit_site(self, url):
        self.send_keys((By.NAME, 'Dwwz'), url)
        return self.get_attribute((By.NAME, 'Dwwz'), 'value')

    # 输入经营范围
    def input_business_scope(self, scope):
        self.send_keys((By.NAME, 'Jyfw'), scope)
        return self.get_attribute((By.NAME, 'Jyfw'), 'value')

    def input_basic_enterprise_info(self,
                                    enterprise_name='泰斯特房产有限公司',
                                    create_date=1,
                                    real_estate_qualification_number='11123111',
                                    qualification_level='一级', email='test@test.com',
                                    legal_representative='泰斯特',
                                    legal_representative_phone_number='16666958595', financial_admin='泰斯特',
                                    financial_admin_phone_number='16666958595',
                                    tax_people='泰斯特', tax_people_phone_number='16666958595', unit_address='泰斯特大街',
                                    unit_site='www.test.com',
                                    business_scope='喂马，劈柴，周游世界......', is_add=True):
        """
        输入企业基本信息

        :param is_add: 是否是添加操作，默认：是
        :param enterprise_name: 企业名称
        :param create_date: 成立日期
        :param real_estate_qualification_number: 房地产资质号
        :param qualification_level: 资质等级
        :param email: 联系人邮箱
        :param legal_representative: 法人代表
        :param legal_representative_phone_number: 法人代表联系方式
        :param financial_admin: 财务负责人
        :param financial_admin_phone_number: 财务负责人联系方式
        :param tax_people: 办税人
        :param tax_people_phone_number: 办税人联系方式
        :param unit_address: 单位地址
        :param unit_site: 单位网址
        :param business_scope: 经营范围
        :return: 是否成功
        :rtype: str
        """

        # 判断是否有更新日志未阅读,有则会有弹窗
        read_date = self.get_read_date(self.taxpayer_id)
        update_date = self.get_update_date()
        if read_date != 'None':
            read_date = datetime.datetime.strptime(read_date, '%Y-%m-%d')
        if update_date != 'None':
            update_date = datetime.datetime.strptime(update_date, '%Y-%m-%d')
        if read_date == 'None' or update_date > read_date:
            # 点击 我已阅读
            btn = (By.XPATH, "//div[@class='layui-layer-content']//button[@class='layui-btn layui-btn-sm qryd_btn']")
            self.click(btn)
            self.logger.info('有未阅读更新日志，点击"我已阅读"成功')

        # 点击企业信息
        self.click_enterprise_info()
        # 输入企业名称
        name = self.input_enterprise_name(enterprise_name)
        # 输入成立日期
        date = self.input_create_date(create_date)
        # 输入房地产资质号
        number = self.input_real_estate_qualification_number(real_estate_qualification_number)
        # 输入资质等级
        level = self.input_qualification_level(qualification_level)
        # 选择行业类型
        type_ = self.select_industry_type()
        # 输入联系人邮箱
        email_ = self.input_email(email)
        # 输入法人代表
        legal_representative = self.input_legal_representative(legal_representative)
        # 输入法人代表联系方式
        legal_representative_phone_number = self.input_legal_representative_phone_number(
            legal_representative_phone_number)
        # 输入财务负责人
        financial_admin = self.input_financial_admin(financial_admin)
        # 输入财务负责人联系方式
        financial_admin_phone_number = self.input_financial_admin_phone_number(financial_admin_phone_number)
        # 输入办税人
        tax_people = self.input_tax_people(tax_people)
        # 输入办税人联系方式
        tax_people_phone_number = self.input_tax_people_phone_number(tax_people_phone_number)
        # 输入单位地址
        unit_address = self.input_unit_address(unit_address)
        # 输入单位网址
        unit_site = self.input_unit_site(unit_site)
        # 输入经营范围
        business_scope = self.input_business_scope(business_scope)

        # 保存
        self.click((By.CLASS_NAME, 'saveBlue'))
        # 获取保存后的提示信息
        locator = (By.XPATH, '//div[@class="layui-layer-content"]')
        self.text_to_be_present_in_text(locator, '保存成功！')
        text = self.get_text(locator)

        # 封装页面数据
        info_page = [name, date, number, level, type_, email_, legal_representative, legal_representative_phone_number,
                     financial_admin, financial_admin_phone_number, tax_people, tax_people_phone_number, unit_address,
                     unit_site, business_scope]
        # 数据库数据
        info_database = self.get_enterprise_basic_info()

        if text == '保存成功！' and info_page == info_database:
            if is_add:
                self.logger.info('新增企业基本信息成功')
            else:
                self.logger.info('修改企业基本信息成功')
            return 'success'
        else:
            if is_add:
                self.logger.error('新增企业基本信息失败')
            else:
                self.logger.error('修改企业基本信息失败')
            self.logger.error(f'提示信息：{text}')
            self.logger.error(f'页面数据：{info_page}')
            self.logger.error(f'表中数据：{info_database}')
            return 'failure'

    def check_create_date(self, date):
        """检查成立日期：成立日期不能大于当前日期"""

        self.click_enterprise_info()
        # 输入日期
        self.send_keys((By.NAME, 'Clrq'), date)

        # 点击保存
        self.click((By.XPATH, "//a[@class='saveBlue jbxxbtns']"))

        # 获取提示信息
        div = (By.ID, 'msgDom')
        self.text_to_be_present_in_text(div, '日期不能大于当前日期！')
        msg = self.get_text(div)
        if msg == '日期不能大于当前日期！':
            self.logger.info('成立日期不能大于当前日期校验成功')
        return msg

    def get_enterprise_basic_info(self, taxpayer_id=base.nsrsbh):
        """根据纳税人识别号查询企业基本信息"""

        conn = self.get_conn()
        cursor = conn.cursor()
        with conn:
            cursor.execute("""
            SELECT t.Nsr,
                   t.Clrq,
                   t.Zzzh,
                   t.Zzdj,
                   (
                       SELECT HY_MC FROM dbo.zd_hy a WHERE a.HY_DM = t.HY_DM
                   ) HY_MC,
                   t.lxryx,
                   t.Frdb,
                   t.Frlxfs,
                   t.Cwfzr,
                   t.Cwlxfs,
                   t.Bsr,
                   t.Bsrlxfs,
                   t.Dwdz,
                   t.Dwwz,
                   t.Jyfw
            FROM dbo.Qyjbxx t
            WHERE t.Nsrsbh = ?
            """, taxpayer_id)
            row = cursor.fetchone()
        return list(row)

    def get_read_date(self, taxpayer_id):
        """根据纳税人识别号查询最后阅读更新日志日期"""
        conn = self.get_conn()
        cursor = conn.cursor()
        with conn:
            cursor.execute('SELECT MAX(readDate) AS readDate FROM LandTax_hebei.dbo.ReadLog  WHERE uname = ?',
                           taxpayer_id)
            row = cursor.fetchone()
        return str(row[0])

    def get_update_date(self):
        """查询最新更新日志日期"""
        conn = self.get_conn()
        cursor = conn.cursor()
        with conn:
            cursor.execute('SELECT MAX(t.UpdateDate) FROM UpdateLog t')
            row = cursor.fetchone()
        return str(row[0])


class Investors(EnterpriseInfo):
    """
    投资人构成
    """

    logger = Logger('Investors').get_log()

    # 添加投资人构成按钮
    def add_investor(self):
        self.click((By.XPATH, '/html[1]/body[1]/div[2]/dl[1]/dt[1]/p[1]/a[2]'))
        self.click((By.CLASS_NAME, 'addTzr'))

    # 输入股东名
    def input_shareholders_name(self, name):
        self.send_keys((By.NAME, 'Gdmc'), name)

    # 获取股东名称
    def get_shareholders_name(self):
        return self.get_attribute((By.XPATH, '//tr[1]//td[2]//div[1]'), 'textContent')

    # 输入证件号码
    def input_id(self, num):
        self.send_keys((By.NAME, 'Zjhm'), num)

    # 输入出资额
    def input_amount_of_contribution(self, fee):
        self.send_keys((By.NAME, 'Cze'), fee)

    # 选择出资方式
    def select_contribution_type(self, option=2):
        locator = (
            By.XPATH, '/html[1]/body[1]/div[3]/div[2]/div[1]/dl[1]/dd[1]/form[1]/div[4]/div[1]/div[1]/div[1]/input[1]')
        self.click(locator)
        if option == 2:
            xpath = '/html[1]/body[1]/div[3]/div[2]/div[1]/dl[1]/dd[1]/form[1]/div[4]/div[1]/div[1]/dl[1]/dd[2]'
        else:
            xpath = '/html[1]/body[1]/div[3]/div[2]/div[1]/dl[1]/dd[1]/form[1]/div[4]/div[1]/div[1]/dl[1]/dd[3]'
        self.click((By.XPATH, xpath))
        return self.get_attribute(locator)

    def input_investor_info(self, name, id_no, fee):
        """输入投资人信息"""

        self.click_enterprise_info()

        # 点击投资人构成按钮
        self.click_investor()

        # 点击添加投资人构成按钮
        self.click((By.XPATH, '/html[1]/body[1]/div[2]/dl[1]/dt[1]/a[1]'))
        self.input_shareholders_name(name)
        self.input_id(id_no)
        self.input_amount_of_contribution(fee)
        self.select_contribution_type()

        # 保存投资人并获取返回的提示信息
        text = self.save()
        time.sleep(1)
        # 保存后获取新增的投资人id
        investor_id = self.get_investor_id(base.nsrsbh, name)
        # 如果有id说明入表成功
        flag = False
        if investor_id:
            flag = True

        # 校验注册资本
        amount_database = self.get_registered_capital(base.nsrsbh)  # 数据库注册资本
        self.click((By.LINK_TEXT, '企业基本信息'))
        locator = (By.NAME, 'Zczb')
        self.text_to_be_present_in_value(locator, amount_database)
        amount_page = self.get_attribute(locator)  # 企业基本信息页面注册资本

        msg = 'failure'
        # 表中有id，提示信息为：保存成功，页面注册资本与数据库一致，则添加成功
        if flag and text == '保存成功！' and amount_page == amount_database:
            msg = 'success'
            self.logger.info('添加投资人构成成功')
        return msg

    def update_investor_info(self, name, no, fee, contribution_type):
        """修改投资人构成"""

        self.click_enterprise_info()

        # 点击投资人构成按钮
        self.click_investor()

        # 点击修改按钮，默认第一条
        self.click((By.XPATH,
                    '/html[1]/body[1]/div[2]/dl[1]/dd[1]/div[2]/div[1]/div[1]/div[2]/table[1]/tbody[1]/tr[1]/td['
                    '8]/div[1]/a[1]/span[1]'))
        self.input_shareholders_name(name)
        self.input_id(no)
        self.input_amount_of_contribution(fee)
        type_ = self.select_contribution_type(contribution_type)
        text = self.save()
        time.sleep(1)
        investor_page = [name, no, fee, type_]
        # 股东名称
        shareholders_name = self.get_shareholders_name()
        # 根据股东名称及纳税人识别号查询投资人信息
        investor_database = self.get_investor(base.nsrsbh, shareholders_name)
        msg = 'failure'
        if text == '保存成功！' and investor_page == investor_database:
            msg = 'success'
            self.logger.info('修改投资人构成成功')
        return msg

    def delete_investor_info(self):
        """删除投资人构成"""

        self.click_enterprise_info()
        self.click_investor()
        get_shareholders_name = self.get_shareholders_name()
        delete_btn = (By.XPATH, '//tr[1]//td[8]//div[1]//a[2]//span[1]')
        flags = self.get_investor_status(base.nsrsbh)

        # 如果投资人都为已删除状态，则无需删除
        if '1' not in flags:
            self.logger.info(f'投资人状态：{flags}，\'1\'：正常 \'2\'：已删除')
            return '投资人全部无效，无需删除'
        # 点击删除
        self.click(delete_btn)
        # 点击确定
        self.click((By.LINK_TEXT, '确定'))
        time.sleep(1)
        # 删除后，该投资人增加备注：本条记录已删除
        remarks = self.get_investor_remarks(base.nsrsbh, get_shareholders_name)
        msg = 'failure'
        if remarks == '本条记录已删除':
            msg = 'success'
            self.logger.info('删除投资人构成成功')
        else:
            self.logger.error('删除投资人构成失败')
            self.logger.error(f'remarks：{remarks}')
        return msg

    def click_investor(self):
        """点击投资人构成按钮"""
        self.click((By.XPATH, '/html[1]/body[1]/div[2]/dl[1]/dt[1]/p[1]/a[2]'))

    def save(self):
        """投资人构成保存按钮"""

        self.click((By.XPATH, '/html[1]/body[1]/div[3]/div[2]/div[1]/div[2]/a[1]'))
        locator = (By.XPATH, '//div[@class="layui-layer-content"]')
        self.text_to_be_present_in_text(locator, '保存成功！')
        return self.get_text(locator)

    def get_investor_id(self, taxpayer_id, shareholder_name):
        """根据纳税人识别号与股东名称查询投资人id"""

        conn = self.get_conn()
        cursor = conn.cursor()
        with conn:
            cursor.execute("SELECT t.IDDJtzrgc FROM dbo.DJtzrgc t WHERE t.Nsrsbh = ? AND t.Gdmc = ?",
                           (taxpayer_id, shareholder_name))
            row = cursor.fetchone()
            investor_id = row[0]
        return investor_id

    def get_investor(self, taxpayer_id, shareholders_name):
        """根据纳税人识别号与股东名称查找投资人"""

        conn = self.get_conn()
        cursor = conn.cursor()
        with conn:
            cursor.execute('SELECT t.Gdmc, t.Zjhm, t.Cze,t.Czfs FROM dbo.DJtzrgc t WHERE t.Nsrsbh = ? and  t.Gdmc = ?',
                           taxpayer_id, shareholders_name)
            investor = cursor.fetchone()
            investor[2] = str(investor[2])
        return list(investor)

    def get_investor_remarks(self, taxpayer_id, shareholders_name):
        """根据纳税人识别号与股东名称查找投资人备注"""

        conn = self.get_conn()
        cursor = conn.cursor()
        with conn:
            cursor.execute('SELECT t.Bz FROM dbo.DJtzrgc t WHERE t.Nsrsbh = ? and t.Gdmc = ?',
                           taxpayer_id, shareholders_name)
            remarks = cursor.fetchone()[0]
        return remarks

    def get_investor_status(self, taxpayer_id):
        """根据纳税人识别号查找投资人状态"""

        conn = self.get_conn()
        cursor = conn.cursor()
        with conn:
            cursor.execute('select t.flag from DJtzrgc t where t.Nsrsbh= ?', taxpayer_id)
            flags = cursor.fetchall()
        return [item[0] for item in flags]

    def get_registered_capital(self, taxpayer_id):
        """根据纳税人识别号查询注册资本合计金额"""

        conn = self.get_conn()
        cursor = conn.cursor()
        with conn:
            cursor.execute('SELECT SUM(t.Cze) FROM DJtzrgc t WHERE t.Nsrsbh = ? AND t.Bz IS NULL', taxpayer_id)
            row = cursor.fetchone()
        return str(row[0])
